package com.itheima.appserver.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.itheima.appserver.config.MyThreadLocal;
import com.itheima.commons.constants.Constants;
import com.itheima.commons.pojo.Publish;
import com.itheima.commons.pojo.UserInfo;
import com.itheima.commons.pojo.Video;
import com.itheima.commons.vo.CommentVo;
import com.itheima.commons.vo.PageResult;
import com.itheima.commons.vo.VideoVo;
import com.itheima.dubbo.interfaces.PublishApi;
import com.itheima.dubbo.interfaces.UserInfoApi;
import org.bson.types.ObjectId;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.commons.pojo.Comment;
import com.itheima.dubbo.interfaces.CommentApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author: lqTao
 * @Date: 2021/12/9 18:53
 */
@Service
public class CommentService {

    @Reference
    CommentApi commentApi;

    @Reference
    PublishApi publishApi;

    @Reference
    UserInfoApi userInfoApi;

    @Autowired
    RedisTemplate<String, String> redisTemplate;


    //i为1是点赞，3是喜欢
    public Long comment(String publishid, int type, Class t) {
        Comment comment = setComment(publishid, type);
        Long count = commentApi.comment(comment, type, t);
        String hashkey;
        String hashkeyStatus;
        if (type == 3) {
            //喜欢
            hashkey = Constants.MOVEMENT_LOVE_HASHKEY;
            hashkeyStatus = Constants.MOVEMENT_ISLOVE_HASHKEY;

        } else {
            //type==1 点赞
            hashkey = Constants.MOVEMENT_LIKE_HASHKEY;
            hashkeyStatus = Constants.MOVEMENT_ISLIKE_HASHKEY;
        }

        //把圈子点赞数存入redis
        redisTemplate.opsForHash().put(Constants.MOVEMENTS_INTERACT_KEY + publishid, hashkey, count.toString());
        //把圈子点赞状态存入redis
        redisTemplate.opsForHash().put(Constants.MOVEMENTS_INTERACT_KEY + publishid, hashkeyStatus + MyThreadLocal.getUserId(), "1");
        return count;
    }

    //i为1是点赞，3是喜欢
    public Long disComment(String publishid, int i, Class t) {

        //有返回值 新生成了一行，有publishid字段了，现在要把他删除
        Long count = commentApi.disComment(MyThreadLocal.getUserId(), new ObjectId(publishid), i, t);
        return count;
    }

    //查询评论
    public PageResult queryComment(String publishId, Integer page, Integer pagesize, Class t) {

        //根据publishId，且type=2，查询userId(评论人id)
        PageResult pageResult = commentApi.queryCommentList(new ObjectId(publishId), page, pagesize, t);

        List items = pageResult.getItems();
        if (CollUtil.isEmpty(items)) {
            //如果没有人评论则直接返回
            return pageResult;
        }

        //有人评论走下面

        //以下不用，想太多
        /*//获取发布人的信息（头像和名称）
        //根据publishId查询朋友圈publishUserId
        Publish publish = publishApi.findPublish(publishId);
        //用publishUserId查询UserInfo,展示信息
        UserInfo userInfo = userInfoApi.findById(publish.getUserId());*/

        //根据评论userId查询对应UserInfo的名称和头像
        List<Long> userIds = CollUtil.getFieldValues(items, "userId", Long.class);
        Map<Long, UserInfo> userInfoMap = userInfoApi.findUserInfoByUserid(new UserInfo(), userIds);


        ArrayList list = new ArrayList<>();

            for (Object item : items) {
                if (t == Comment.class) {
                    Comment comment = (Comment) item;
                    CommentVo commentVo = new CommentVo();
                    //评论id
                    commentVo.setId(comment.getId().toHexString());
                    commentVo.setContent(comment.getContent());
                    commentVo.setCreateDate(DateUtil.format(new Date(comment.getCreated()), "HH:mm"));

                    //查询评论人用户信息
                    UserInfo userInfo1 = userInfoMap.get(comment.getUserId());
                    //用户图像
                    commentVo.setAvatar(userInfo1.getLogo());
                    //用户名
                    commentVo.setNickname(userInfo1.getNickName());

                    ObjectId publishid = comment.getPublishId();

                    Map<String, Object> map = redisOps(publishid, t);
                    commentVo.setLikeCount(Convert.toInt(map.get("likeCount")));
                    commentVo.setHasLiked((Boolean) map.get("isLike") ? 1 : 0);
                    list.add(commentVo);
                } else if(t == Video.class){
                    Video video = (Video) item;
                    VideoVo videoVo = new VideoVo();
                    videoVo.setId(video.getId().toHexString());
                    videoVo.setCover(video.getPicUrl());
                    videoVo.setVideoUrl(video.getVideoUrl());
                    //查询评论人用户信息
                    UserInfo userInfo1 = userInfoMap.get(video.getUserId());

                    videoVo.setUserId(userInfo1.getUserId());
                    videoVo.setAvatar(userInfo1.getLogo());
                    videoVo.setNickname(userInfo1.getNickName());

                    videoVo.setLikeCount(0);
                    videoVo.setHasLiked(0);
                    videoVo.setHasFocus(0);
                    videoVo.setCommentCount(0);
                    ObjectId publishid = video.getId();

                    Map<String, Object> map = redisOps(publishid, t);
                    videoVo.setLikeCount(Convert.toInt(map.get("likeCount")));
                    videoVo.setHasLiked((Boolean) map.get("isLike") ? 1 : 0);

                    list.add(videoVo);

                    // 是否关注
                    videoVo.setHasFocus(redisTemplate.opsForSet().isMember(Constants.VIDEO_FOLLOW_HASHKEY + MyThreadLocal.getUserId(), userInfo1.getUserId().toString()) ? 1 : 0);

                }
            }
        pageResult.setItems(list);
        return pageResult;
    }

    public Map<String, Object> redisOps(ObjectId publishid, Class t) {
        //把圈子点赞数从redis取出
        Long likeCount = (Long) redisTemplate.opsForHash().get(Constants.MOVEMENTS_INTERACT_KEY + publishid, Constants.MOVEMENT_LIKE_HASHKEY);
        if (ObjectUtil.isNull(likeCount)) {
            //如果为空， 1、点赞数为0
            //      或2、redis无该数据
            likeCount = commentApi.queryComment(publishid, 2, t);
            redisTemplate.opsForHash().put(Constants.MOVEMENTS_INTERACT_KEY + publishid, Constants.MOVEMENT_LIKE_HASHKEY, likeCount.toString());
        }


        //把圈子点赞状态从redis取出
        Boolean isLike = redisTemplate.opsForHash().hasKey(Constants.MOVEMENTS_INTERACT_KEY + publishid, Constants.MOVEMENT_ISLIKE_HASHKEY + MyThreadLocal.getUserId());

        if (!isLike) {
            //1、可能没点赞
            //2、redis中没数据

            //从mongodb查询是否喜欢
            isLike = commentApi.queryCommentStatus(publishid, 2, MyThreadLocal.getUserId(), t);
            if (isLike) {
                //进入到这，表示点赞了，把圈子点赞状态存入redis
                redisTemplate.opsForHash().put(Constants.MOVEMENTS_INTERACT_KEY + publishid, Constants.MOVEMENT_ISLIKE_HASHKEY + MyThreadLocal.getUserId(), "1");
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("likeCount", likeCount);
        map.put("isLike", isLike);

        return map;
    }

    //提交评论
    public void commitComment(Map<String, Object> params) {
        ObjectId publishId = (ObjectId) params.get("movementId");
        String com = (String) params.get("comment");

        //根据publishId查询是哪个用户发布的（userId）
        Publish publish = publishApi.findPublish(publishId);
        Long userId = publish.getUserId();

        Comment comment = new Comment();
        //主键id
        comment.setId(new ObjectId());
        //根据publishId找到对应的_id，_id就是publishId
        comment.setPublishId(publishId);
        comment.setCommentType(2);
        comment.setContent(com);
        comment.setUserId(MyThreadLocal.getUserId());
        //发布动态用户id
        comment.setPublishUserId(userId);

        comment.setCreated(System.currentTimeMillis());

        commentApi.saveComment(comment);

    }

    //对朋友圈和短视频评论
    public Comment setComment(String publishid, int type) {
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(publishid));
        comment.setCommentType(type);
        comment.setUserId(MyThreadLocal.getUserId());
        comment.setCreated(System.currentTimeMillis());

        Publish publish = publishApi.findPublish(new ObjectId(publishid));

        if (ObjectUtil.isNotNull(publish)) {
            //进入到这说明publishId为朋友圈id
            comment.setPublishUserId(publish.getUserId());
        } else {
            //进入到这说明publishId不是朋友圈id，而是朋友圈的评论或小视频的点赞
            Comment com = commentApi.queryComment(new ObjectId(publishid));
            //把publishid重新赋值了，确保一定是表中的publishid值
            publishid = Convert.toStr(com.getPublishId());
            comment.setPublishUserId(com.getUserId());
        }

        return comment;
    }
}
